var helper = {
    // 设置viewport
    android_fit: function(a) {
        if (/Android (\d+\.\d+)/.test(navigator.userAgent)) {
            document.write('<meta name="viewport" content="width=' + a + ',target-densitydpi=device-dpi,user-scalable=no" />');
        } else {
            document.write('<meta name="viewport" content="width=' + a + ', user-scalable=no">')
        }
    },
    // 是否登录
    isLogin: function() {
        var identityObj = helper._store("identity");
        if (identityObj && identityObj.admin_id && identityObj.token) {
            return true;
        }
        return false;
    },
    /**
     * [isLogout  清除用户信息]
     */
    isLogout: function() {
        sessionStorage.removeItem('menu_tree')
        localStorage.removeItem('identity')
    },
    // 登陆回跳
    gotoLogin: function() {
        location.href = 'http://' + getApiDomain() + '/wx/index/auth?topage=' + encodeURIComponent(location.href);
    },
    // 自由跳转
    gotoUrl: function(url_to) {
        location.href = 'http://' + TQ._domains.main + url_to;
    },
    //****************************************************************
    //* 名　　称：IsEmpty
    //* 功    能：判断是否为空
    //* 入口参数：fData：要检查的数据
    //* 出口参数：True：空
    //*           False：非空
    //*****************************************************************
    isEmpty: function(v) {
        switch (typeof v) {
            case 'undefined':
                return true;
            case 'string':
                if (v.replace(/(^[ \t\n\r]*)|([ \t\n\r]*$)/g, '').length == 0) return true;
                break;
            case 'boolean':
                if (!v) return true;
                break;
            case 'number':
                if (0 === v || isNaN(v)) return true;
                break;
            case 'object':
                if (null === v || v.length === 0) return true;
                for (var i in v) {
                    return false;
                }
                return true;
        }
        return false;
    },
    /**
     * 验证手机号
     * @param  {[string]}  phone [手机号码]
     * @return {Boolean}
     */
    isPhoneNum: function(phone) {
        // 手机号正则
        var reg = /^1[3|4|5|6|7|8][0-9]\d{8}$/;
        if (reg.test(phone)) {
            return true;
        }
        return false;
    },

    tipWin: function(tip, time) {
        var time = time|60
        jQuery.gritter.add({
            title: tip,
            sticky: false,
            class_name: 'growl-waring gritter-center',
            time: time
        });
    },
    /***
     * 本地化存储数据，
     * @param key   string类型
     * @param obj   存储非函数类型的对象，不深度拷贝
     * @private
     */
    _store: function(key, obj) {
        var value;
        // 因为open_id和手机号是关系断开的,所以,暂时用localstorage忽悠一下.
        //优先使用localstorege,其次使用cookie,
        if (window.localStorage) {
            if (obj) {
                if (typeof obj == "object") {
                    window.localStorage.setItem(key, JSON.stringify(obj));
                } else if (typeof obj == "string") {
                    window.localStorage.setItem(key, obj);
                } else {
                    tip("_storeByBrowser:你存储的是非对象");
                }
            } else {
                try {
                    value = JSON.parse(window.localStorage.getItem(key));
                } catch (e) {
                    return window.localStorage.getItem(key);
                }
            }
        } else { //使用cookie
            TQ.cookie('test', 'test');
            if (!document.cookie || document.cookie == '') {
                //tip('请设置您的浏览器支持cookie以便正常访问');暂时放空
                if (obj) {
                    value = TQ._store(key, obj);
                } else {
                    value = TQ._store(key);
                }
            } else {
                if (obj) {
                    if (typeof obj == "object") {
                        value = TQ.cookie(key, JSON.stringify(obj));
                    } else if (typeof(obj) == "string" || typeof(obj) == "number") {
                        value = TQ.cookie(key, obj);
                    } else {
                        alert("localStorage:你存储的是非对象");
                    }
                } else {
                    try {
                        value = JSON.parse(TQ.cookie(key));
                    } catch (e) {
                        value = TQ.cookie(key);
                    }
                }
            }
        }
        return value;
    },
    _sess: function(key, obj) {
        if (window.sessionStorage) {
            if (obj) {
                if (typeof obj == "object") {
                    window.sessionStorage.setItem(key, JSON.stringify(obj));
                } else if (typeof(obj) == "string" || typeof(obj) == "number") {
                    window.sessionStorage.setItem(key, obj);
                } else {
                    alert("sessionStorage:你存储的是非对象");
                }
            } else {
                try {
                    return JSON.parse(window.sessionStorage.getItem(key));
                } catch (e) {
                    return window.sessionStorage.getItem(key);
                }
            }
        } else {
            console.info('sessionStorage not for ready!');
        }
    },
    /**
     * 字符串序列化为对象
     * @method str2Args
     * @param {String} 待分割字符串
     * @param {String} 分隔符
     */
    str2Args: function(query, split) {
        var args = {};
        query = query || '';
        split = split || '&';
        var pairs = query.split(split);
        for (var i = 0; i < pairs.length; i++) {
            var pos = pairs[i].indexOf('=');
            if (pos == -1) {
                continue;
            }
            var argname = pairs[i].substring(0, pos).replace(/amp;/, "");
            var value = pairs[i].substring(pos + 1);
            args[argname] = decodeURIComponent(value);
        }
        return args;
    },
    array_merge: function(a, c) {
        // 数组合并,从c&&a的并集
        var d = {},
            b;
        for (b in a) d[b] = a[b];
        for (b in c) d[b] = c[b];
        return d
    },
    in_array: function(search, array) {
        // 数组存在判断
        for (var i in array) {
            if (array[i] == search) {
                return true;
            }
        }
        return false;
    },
    jlog: function(obj) {
        var log = JSON.stringify(obj);
        // 以json格式打日志
        //console.log(log);
        return log;
    },
    isHttps: function() {
        var url = window.location.href;
        var isHttps = url.toUpperCase().indexOf("HTTPS");
        if (isHttps > -1) {
            return true;
        }
        return false;
    },
    getProtocol: function() {
        if (helper.isHttps()) {
            return "https"
        }
        return "http";
    },
    // 时间戳转日期
    timeStampToDate: function(seconds, f) {
        if(seconds == 0 )
            return ''
        var md = new Date(1e3 * parseInt(seconds));
        var hour = md.getHours();
        var minutes = md.getMinutes();
        if (hour <= 9) {
            hour = "0" + hour;
        }
        if (minutes <= 9) {
            minutes = "0" + minutes;
        }
        if (f == 'day') {
            return md.getFullYear() + "年" + (md.getMonth() + 1) + "月" + md.getDate() + '日';
        } else if (f == 1) {
            return (md.getMonth() + 1) + "-" + md.getDate();
        } else if (f == 2) {
            return md.getFullYear() + "-" + (md.getMonth() + 1) + "-" + md.getDate();
        } else {
            return md.getFullYear() + "/" + (md.getMonth() + 1) + "/" + md.getDate() + " " + hour + ":" + minutes;
        }
    },
    // 日期转时间戳
    dateToTimeStamp: function(stringTime) {
        // 转为时间戳,秒
        // 正确 var stringTime = '2013/07/10';
        // 不允许 var stringTime = '2013/9/7';
        // var stringTime = '2013/07/10 10:01:01';
        if (stringTime) {
            var timestampNs = Date.parse(new Date(stringTime));
            timestamp = timestampNs / 1000;
        } else {
            timestamp = 0;
        }
        return timestamp;
    },
    // 异步请求封装
    xhr_get: function(uri, cb) {
        var xhr;
        if (window.XMLHttpRequest) {
            xhr = new XMLHttpRequest();
        } else {
            xhr = new ActiveXObject('Microsoft.XMLHTTP');
        }
        //异步接受响应
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    cb(xhr.responseText);
                }
            }
        }
        // get请求
        xhr.open('get', uri, true);
        xhr.send();
    },
    // 异步post请求封装
    xhr_post: function(uri, req, cb) {
        var xhr;
        if (window.XMLHttpRequest) {
            xhr = new XMLHttpRequest();
        } else {
            xhr = new ActiveXObject('Microsoft.XMLHTTP');
        }
        //异步接受响应
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    cb(xhr.responseText);
                }
            }
        }
        // get请求
        xhr.open('post', uri, true);
        var formdata = new FormData();
        //formdata.append('param', helper.jlog(req));
        for (var key in req){
            formdata.append(key,req[key]);
        }

        xhr.send(formdata);
    },
    parse_url: function(url) {
        var a = document.createElement('a');
        a.href = url;
        return {
            source: url,
            protocol: a.protocol.replace(':', ''),
            host: a.hostname,
            port: a.port,
            query: a.search,
            file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1],
            hash: a.hash.replace('#', ''),
            path: a.pathname.replace(/^([^\/])/, '/$1'),
            relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1],
            segments: a.pathname.replace(/^\//, '').split('/'),
            params: (function() {
                var ret = {};
                var seg = a.search.replace(/^\?/, '').split('&').filter(function(v, i) {
                    if (v !== '' && v.indexOf('=')) {
                        return true;
                    }
                });
                seg.forEach(function(element, index) {
                    var idx = element.indexOf('=');
                    var key = element.substring(0, idx);
                    var val = element.substring(idx + 1);
                    ret[key] = val;
                });
                return ret;
            })()
        };
    },
    check_login_router: function() {
        var router_not_check = ['login.html']
        if ($.inArray(helper.parse_url(window.TQ.current_url).file, router_not_check) == -1) {
            return false
        }
        return true;
    },
    base64Decode: function(data) {
        return data;
    }
}
//Base64编码
var Base64 = {
    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
    encode: function(e) {
        var t = "";
        var n, r, i, s, o, u, a;
        var f = 0;
        e = Base64._utf8_encode(e);
        while (f < e.length) {
            n = e.charCodeAt(f++);
            r = e.charCodeAt(f++);
            i = e.charCodeAt(f++);
            s = n >> 2;
            o = (n & 3) << 4 | r >> 4;
            u = (r & 15) << 2 | i >> 6;
            a = i & 63;
            if (isNaN(r)) {
                u = a = 64
            } else if (isNaN(i)) {
                a = 64
            }
            t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a)
        }
        return t
    },
    decode: function(e) {
        var t = "";
        var n, r, i;
        var s, o, u, a;
        var f = 0;
        e = e.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (f < e.length) {
            s = this._keyStr.indexOf(e.charAt(f++));
            o = this._keyStr.indexOf(e.charAt(f++));
            u = this._keyStr.indexOf(e.charAt(f++));
            a = this._keyStr.indexOf(e.charAt(f++));
            n = s << 2 | o >> 4;
            r = (o & 15) << 4 | u >> 2;
            i = (u & 3) << 6 | a;
            t = t + String.fromCharCode(n);
            if (u != 64) {
                t = t + String.fromCharCode(r)
            }
            if (a != 64) {
                t = t + String.fromCharCode(i)
            }
        }
        t = Base64._utf8_decode(t);
        return t
    },
    _utf8_encode: function(e) {
        e = e.replace(/\r\n/g, "\n");
        var t = "";
        for (var n = 0; n < e.length; n++) {
            var r = e.charCodeAt(n);
            if (r < 128) {
                t += String.fromCharCode(r)
            } else if (r > 127 && r < 2048) {
                t += String.fromCharCode(r >> 6 | 192);
                t += String.fromCharCode(r & 63 | 128)
            } else {
                t += String.fromCharCode(r >> 12 | 224);
                t += String.fromCharCode(r >> 6 & 63 | 128);
                t += String.fromCharCode(r & 63 | 128)
            }
        }
        return t
    },
    _utf8_decode: function(e) {
        var t = "";
        var n = 0;
        var r = c1 = c2 = 0;
        while (n < e.length) {
            r = e.charCodeAt(n);
            if (r < 128) {
                t += String.fromCharCode(r);
                n++
            } else if (r > 191 && r < 224) {
                c2 = e.charCodeAt(n + 1);
                t += String.fromCharCode((r & 31) << 6 | c2 & 63);
                n += 2
            } else {
                c2 = e.charCodeAt(n + 1);
                c3 = e.charCodeAt(n + 2);
                t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63);
                n += 3
            }
        }
        return t
    }
};
// 处理异常
var errHandler = function(e){
    console.log(e)
    $('[type=submit]', 'form').removeClass('disabled');
    //如果token 错误 // 跳转登录处理
    if (e.extra.res.data.code == 10001) {
        helper.isLogout();
        if (!helper.check_login_router()) {
            helper.gotoLogin();
        }
        return false
    }
    if(e.extra.res.data.code == 10002){
        return false;
    }
    helper.tipWin(e.extra.res.msg, 3000)
    return false;
}

function Excp(message, code, extra) {
    this.message = message || 'unknown error';
    this.code = code || 500;
    this.extra = extra || {};
    this.getCode = function() {
        return this.code;
    }
    this.getMessage = function() {
        return this.message;
    }
    this.getExtra = function() {
        return this.extra;
    }
}
// 异步请求
var doRequestwithnoheader = function(req) {
    var errorHandler = errHandler
    return new Promise(function(resolve, reject) {
        if(!req.serverName){
            throw new DOMException('没有接口地址')
        }
        ajax_send(req.serverName, req).then(function(res) {
            resolve(res)
        }, errorHandler)
    })
};

function  getApiDomain(){
    return location.host == 'line.h5.com'?'line.admin.com':'';
}

// 系统方法
var ajax_send = function(api, req) {
    if (req) {
        // 注入自然指纹
        var identityObj = helper._store("identity");
        if (!helper.isEmpty(identityObj)) {
            req.admin_id = identityObj.admin_id;
            req.token = identityObj.token;
            req.club_id = identityObj.club_id;
        } else {
            req.admin_id = "";
        }
        // req.admin_id = 1
        // req.token = 1
        // 全局参数,有则注入
        var global_param = helper._store('global_param');
        req = helper.array_merge(req, global_param);
    }
    // 覆盖最新版本号
    req.version = '1.0';
    var uri = '//' + getApiDomain() + api;
    return new Promise(function(resolve, reject) {
        helper.xhr_post(uri, req, function(res) {
            var json = JSON.parse(res);
            if (json.code  != 200) {
                // 如果是错误的用户指纹,需要清指纹并重新登陆
                if (json.code == 10000) {
                    helper._store('identity', {});
                    helper.gotoLogin();
                }
                reject(new Excp(json['msg'], 500, {
                    res: json,
                    api: uri,
                    data: req,
                }));
                return;
            }
            resolve(json);
        });
    })
}
// 全局变量统一定义
var t_paramsArr = window.location.href.split("?");
var g_paramsStr = t_paramsArr.length > 1 ? t_paramsArr[1] : "";
var g_params = helper.str2Args(g_paramsStr, "&");
// api网关
var g_host_api = '//' + location.host + '/api/';
var protocol = helper.getProtocol();
// 自动跳转,登陆态注入
if (g_params.admin_id && g_params.token) {
    var identity = {
        admin_id: g_params.admin_id,
        token: g_params.token
    }
    console.log('login_success#', identity);
    helper._store("identity", identity);
}
window.TQ = {
    debug: function() {
        return true;
    },
    _domains: {
        main: window.location.host,
        imgcache: protocol + "://upload.jjys168.com",
        api: g_host_api
    },
    current_url: window.location.href.split('?')[0],
    set_host_api: function(uri) {
        this._domains.api = protocol + '://' + uri;
    },
    identityObj: helper._store("identity")
};
var autoload = (function() {
    /*缓存登陆信息*/
    if(g_params['user_id'] && g_params['token']){
        helper._store("identity",{admin_id:g_params['user_id'],token:g_params['token']})
    }

    /*判断是否有登陆*/
    if(!helper.isLogin()){
        helper.gotoLogin();
    }
 })(autoload);

// 模板相关定制
template.openTag = '{{';
template.closeTag = '}}';
// 一键注入,请勿模仿;
template.helper('helper', function() {
    return helper;
});
template.helper('json2stringify', function(obj) {
    return JSON.stringify(obj);
});
// 转换为数字
template.helper('Number', function(s) {
    return Number(s);
});

template.helper('Price', function(s) {
    return (s/100).toFixed(2)
});


